package com.open.yujiakj.core.utils.mybatis;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 反射工具类
 *
 * @author wanbx
 * @date 2022-02-18
 */
@Slf4j
public class ReflexUtils {


    /**
     * 通过反射获取Field集合
     *
     * @param clazz 当前类
     * @return
     */
    public static List<Field> getFieldsInfo(Class clazz) {

        List fieldsList = new ArrayList<Field[]>();
        try {
            while (clazz != null) {
                //获取字节码对象的属性对象数组
                Field[] declaredFields = clazz.getDeclaredFields();
                fieldsList.add(declaredFields);
                //获得父类的字节码对象
                clazz = clazz.getSuperclass();
            }
            fieldsList.remove(fieldsList.size() - 1);
        } catch (Exception e) {
            log.error("getFieldsInfo exception-{}", e.getMessage());
        }
        return fieldsList;
    }

    /**
     * 前端排序字段通过反射获取属性转数据库字段
     *
     * @param className      入参类
     * @param sortColumnName 排序字段
     * @return TableField 注解值
     */
    public static String getFieldValueByName(String className, String sortColumnName) {

        String resultColumn = "";
        boolean flag = false;//循环标记
        try {

            List<Field> fieldList = ReflexUtils.getFieldsInfo(Class.forName(className));
            //打印当前类以及其父类的多有属性对象
            for (Object fields : fieldList) {
                if (flag) {
                    break;
                }
                Field[] f = (Field[]) fields;
                for (Field field : f) {
                    String cName = toLowerCaseFirstOne(sortColumnName);
                    if (field.getName().equals(cName)) {
                        field.setAccessible(true);
                        TableField tableField = field.getAnnotation(TableField.class);
                        resultColumn = tableField.value();
                        flag = true;
                        break;
                    } else if ("id".equals(cName.toLowerCase())) {
                        field.setAccessible(true);
                        TableId tableField = field.getAnnotation(TableId.class);
                        resultColumn = tableField.value();
                        flag = true;
                        break;
                    }
                }
            }

        } catch (ClassNotFoundException e) {
            log.error("getFieldValueByName Field convert exception-{}", e.getStackTrace());
        }

        return resultColumn == "" ? sortColumnName : resultColumn;
    }

    /**
     * 字段首字母转小写
     */
    public static String toLowerCaseFirstOne(String columnName) {
        if (Character.isLowerCase(columnName.charAt(0))) {
            return columnName;
        } else {
            return (new StringBuilder()).append(Character.toLowerCase(columnName.charAt(0))).append(columnName.substring(1)).toString();
        }
    }

    /**
     * 最终要导出的数据
     *
     * @param dataList
     * @param exportColumns
     * @return
     */
    public static List<Map<String, Object>> getFinalData(List<Map<String, Object>> dataList, Map<String, String> exportColumns) {

        List<Map<String, Object>> finalData = new ArrayList<>();
        try {
            // 属性Name匹配标题,finalData最终要导出的数据
            dataList.stream().forEach(d -> {
                Map<String, Object> map = new LinkedHashMap<>();
                exportColumns.forEach((key, value) -> {
                    map.put(value, d.get(key));
                });
                finalData.add(map);
            });
        } catch (Exception e) {
            log.error("getFinalData exception-{}", e.getStackTrace());
        }
        return finalData;
    }

}
